package com.example.demo.demo.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * PreparedStatement
 *
 * @author: htc
 * @date: Created in 16:48 2018/11/2.
 */
public class Demo3 {

    public static void main(String[] args) throws Exception {
//        insert();
        select();
    }

    /**
     * insert update delete
     *
     * @throws SQLException
     */
    public static void insert() throws SQLException {
        System.out.println("#########   insert  #########");
        Connection con = null;
        PreparedStatement pstmt = null;
        int count = 0;
        try {
            //1、获取连接
            con = JdbcUtil.getConnection();

            //2、准备预编译SQL语句
            String sql = "insert into app.demo(id,name) values(?,?)";

            //3、执行预编译SQL语句（检查语法）
            pstmt = con.prepareStatement(sql);

            //4、设置参数值(第一个参数从1开始)
            pstmt.setInt(1, 5);
            pstmt.setString(2, "玲");

            //5、发送参数，执行SQL
            count = pstmt.executeUpdate();

            System.out.println(count);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeResource(con, pstmt);
        }
    }


    /**
     * insert update delete
     *
     * @throws SQLException
     */
    public static void select() throws Exception {
        System.out.println("#########   select  #########");
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            //1、获取连接
            con = JdbcUtil.getConnection();

            //2、准备预编译SQL语句
            String sql = "SELECT * FROM app.demo where name=?";

            //3、执行预编译（检查语法）
            pstmt = con.prepareStatement(sql);

            //4、设置参数值(第一个参数从1开始)
            pstmt.setString(1, "or 1=1");

            //5、发送参数，执行SQL
            rs = pstmt.executeQuery();

            while (rs.next()) {
                System.out.print(rs.getString("id"));
                System.out.println(rs.getString("name"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeResource(con, pstmt, rs);
        }
    }
}
